#include <QMessageBox>
#include <QFileInfo>
#include <QAction>
#include <QMenu>
#include <QFileDialog>

#include "singletab.h"

void SingleTab::contextMenuEvent(QContextMenuEvent *event)
{
    QWebHitTestResult r = page()->mainFrame()->hitTestContent(event->pos());
    if (!r.linkUrl().isEmpty()) {
        link=r.linkUrl();
        QMenu menu(this);
        menu.addAction(pageAction(QWebPage::OpenLinkInNewWindow));
        menu.addAction(tr("Open in New Tab"), this, SLOT(openLinkInNewTab(bool)));
        menu.addSeparator();
        menu.addAction(pageAction(QWebPage::DownloadLinkToDisk));
        menu.addAction(tr("Save link into home folder"), this, SLOT(saveLinkIntoFolder()));
       // menu.addAction(tr("URIEL IS BRITE"), this, SLOT(saveLinkIntoFolder()));
        menu.addAction(pageAction(QWebPage::DownloadLinkToDisk));
        menu.addSeparator();
        menu.addAction(pageAction(QWebPage::CopyLinkToClipboard));
        if (page()->settings()->testAttribute(QWebSettings::DeveloperExtrasEnabled))
            menu.addAction(pageAction(QWebPage::InspectElement));
        menu.exec(mapToGlobal(event->pos()));
        return;
    }
    QWebView::contextMenuEvent(event);
}

void SingleTab::saveLinkIntoFolder()
{
    pageAction(QWebPage::DownloadLinkToDisk)->trigger();
    progressDialog = new QProgressDialog(this);
    connect(progressDialog, SIGNAL(canceled()), this, SLOT(cancelDownload()));
    http = new QHttp(this);
    QUrl url(link);
    QFileInfo fileInfo(url.path());
    QString fileName = fileInfo.fileName();
    if (fileName.isEmpty())
    {

                fileName = QFileDialog::getOpenFileName(this,
     tr("Save File"), "~/", tr("File name (*)"));
                ;
    }

     //   fileName = "index.html";
    if (QFile::exists(fileName)) {
        if (QMessageBox::question(this, tr("HTTP"),
                                  tr("There already exists a file called %1 in "
                                  "the current directory. Overwrite?").arg(fileName),
                                  QMessageBox::Ok|QMessageBox::Cancel, QMessageBox::Cancel)
                                  == QMessageBox::Cancel)
            return;
        QFile::remove(fileName);
    }
    file = new QFile(fileName);
    connect(http, SIGNAL(requestFinished(int, bool)), this, SLOT(httpRequestFinished(int, bool)));
    connect(http, SIGNAL(dataReadProgress(int, int)), this, SLOT(updateDataReadProgress(int, int)));
    connect(http, SIGNAL(responseHeaderReceived(const QHttpResponseHeader &)), this, SLOT(readResponseHeader(const QHttpResponseHeader &)));
    connect(progressDialog, SIGNAL(canceled()), this, SLOT(cancelDownload()));
    if (!file->open(QIODevice::WriteOnly)) {
        QMessageBox::information(this, tr("HTTP"),
                                 tr("Unable to save the file %1: %2.")
                                 .arg(fileName).arg(file->errorString()));
        delete file;
        file = 0;
        return;
    }
    QHttp::ConnectionMode mode = url.scheme().toLower() == "https" ? QHttp::ConnectionModeHttps : QHttp::ConnectionModeHttp;
    http->setHost(url.host(), mode, url.port() == -1 ? 0 : url.port());
    if (!url.userName().isEmpty())
        http->setUser(url.userName(), url.password());
    httpRequestAborted = false;
    QByteArray path = QUrl::toPercentEncoding(url.path(), "!$&'()*+,;=:@/");
    if (path.isEmpty())
        path = "/";
    httpGetId = http->get(path, file);
    progressDialog->setWindowTitle(tr("Medusa - Download"));
    progressDialog->setLabelText(tr("Downloading %1.").arg(fileName));
}

void SingleTab::httpRequestFinished(int requestId, bool error)
{
    if (requestId != httpGetId)
        return;
    if (httpRequestAborted) {
        if (file) {
            file->close();
            file->remove();
            delete file;
            file = 0;
        }
        progressDialog->hide();
        return;
    }
    if (requestId != httpGetId)
        return;
    progressDialog->hide();
    file->close();
    if (error) {
        file->remove();
        QMessageBox::information(this, tr("HTTP"),
                                 tr("Download failed: %1.")
                                 .arg(http->errorString()));
    } else {
        QString fileName = QFileInfo(QUrl(link).path()).fileName();
    }
    delete file;
    file = 0;
}
